#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define NUM 4
int g_val = 100;

//定义全局变量锁

pthread_mutex_t pht;


void* mythead(void* arg)
{
    (void)arg;
    while(1)
    {
        //加锁
        pthread_mutex_lock(&pht);
        if(g_val >= 0)
        {
            printf("i am %p,i get tickts:%d\n",pthread_self(),g_val);
            g_val--;
        }
        else 
        {
            pthread_mutex_unlock(&pht);
            break;
        }
        //解锁
        pthread_mutex_unlock(&pht);
    }
    return NULL;

}

int main()
{
    //初始化锁
    pthread_mutex_init(&pht,NULL);
    pthread_t pit[NUM];
    for(int i = 0;i < NUM;i++)
    {
        int ret =  pthread_create(&pit[i],NULL,mythead,NULL);
        if(ret != 0)
        {
            return 0;
        }
    }
    for(int i = 0;i < NUM;i++)
    {
        pthread_join(pit[i],NULL);
    }
    //销毁锁
    pthread_mutex_destroy(&pht);
    return 0;

}
